import axios from "axios";
import store from '../store';

const instance = axios.create({
    baseURL: 'http://localhost:3000/api',
    timeout: 5000,
});

// 添加请求拦截器
instance.interceptors.request.use(
    config => {
        const token = store.state.Authorization;
        if (token) {
            config.headers.Authorization = token;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// 添加响应拦截器
instance.interceptors.response.use(
    response => {
        const newToken = response.data.token;
        if (newToken) {
            // 更新 Vuex 存储的 token
            store.dispatch('updateToken', `Bearer ${newToken}`);
            // 更新本地存储
            localStorage.setItem('Authorization', `Bearer ${newToken}`);
        }
        return response;
    },
    error => {
        if (error.response && (error.response.status === 401 || error.response.status === 403)) {
            store.dispatch('logout');
        }
        return Promise.reject(error);
    }
);

export default instance;